<?php

/*
 *
 * Main class for sorter
 *
 */

require_once "functions/imdb_api.php";
require_once "functions/tvrage.php";

class sort_main {

    private $ommit = array(".", "..");
    private $for_replace = array(".", "_");
    private $for_replace2 = array("[3d]", "(3d)", " 3d ", "[", "]", "\{", "\}", "(", ")");
    private $months = array(
        "jan" => "01",
        "feb" => "02",
        "mar" => "03",
        "apr" => "04",
        "may" => "05",
        "jun" => "06",
        "jul" => "07",
        "aug" => "08",
        "sep" => "09",
        "oct" => "10",
        "nov" => "11",
        "dec" => "12",
        "january" => "01",
        "february" => "02",
        "march" => "03",
        "april" => "04",
        "may" => "05",
        "june" => "06",
        "july" => "07",
        "august" => "08",
        "sepember" => "09",
        "october" => "10",
        "november" => "11",
        "december" => "12",
    );
//    private $allowed_extensions = array("avi", "mkv", "mp4", "mpg", "mpeg", "vob", "ts");
    private $qualities = array('cam', 'camrip', 'screener', 'telesync', '320p', 'ts', 'dvdscr', 'r5', '480p', 'dvdrip', 'dvdr', '720p', '1080p');
    private $config = NULL;
    private $os = NULL;
    private $imdb = NULL;
    public $imdb_info = NULL;
    private $tags = NULL;
    private $log = NULL;
    private $tvrage = NULL;
    public $quality = NULL;
    private $files = NULL;
    public $filter_reject_reason = NULL;

    /**
     * Constructor for sort_main class
     *
     * @param type $config passed config
     * @param type $db instanced db
     */
    public function __construct($config, $db, $log) {
        $this->config = $config;
        // not really a good detection, as it might be OSX or something else
        if (defined('PHP_WINDOWS_VERSION_MAJOR'))
            $this->os = "windows";
        else
            $this->os = "linux";
        $this->imdb = new imdb_api;
        $this->db = $db;
        $this->log = $log;
        $this->tvrage = new tvrage;
        if (!class_exists("files"))
            require_once "functions/files.php";
        $this->files = new files($this->config);
    }

    public function get_imdb() {
        if ($imdb)
            return $this->imdb;
    }

    public function getsize($filename) {
        if (!file_exists($filename))
            return false;
        if (@class_exists("COM")) {
            // Use the Windows COM interface
            $fsobj = new COM('Scripting.FileSystemObject');
            $f = $fsobj->GetFile($filename);
            return (string) $f->Size;
        } else
        if (@function_exists("curl_init")) {
            $ch = curl_init("file://" . $filename);
            if (!$ch) {
                $this->log->addmessage("curl_init didn't succeed");
                return false;
            }
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, true);
            $data = curl_exec($ch);
            curl_close($ch);
            if (!$data) {
                $this->log->addmessage("Curl didn't worked on {$filename}");
            } else
            if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
                return (string) $matches[1];
            }
            else
                $this->log->addmessage("No Content-Length on Curl for {$filename}");
        }
        else
            $this->log->addmessage("No supported way to get big file size! (COM,CURL)");
    }

    /**
     * Process folder found in incoming folder
     *
     * @param type $basedir
     * @param type $subfolder
     * @return boolean|string
     */
    private function process_subfolder($basedir, $subfolder) {
        if (empty($subfolder))
            return false;
        $processed = array();
        foreach ($subfolder as $item => $val) {
            if ($val["directory"])
                continue;
            $extension = $this->files->extract_extension($val["name"]);
            if (in_array($extension, $this->config["Processing"]["allowed_formats"]))
                if ($this->config["Processing"]["delete_sample"] && strstr(strtolower($val["name"]), "sample"))
                    continue;
                else
                    $processed[] = $basedir . $val["name"];
        }
        return $processed;
    }

    private function download_metadata($path, $movieinfo) {
        if (!$movieinfo)
            return false;
        if ($movieinfo->code == 404 || !empty($movieinfo->$error))
            return false;
        $metadata = "<movie>\n";
        $metadata.="<title>{$movieinfo[0]->title}</title>\n";
        $metadata.="    <originaltitle>{$movieinfo[0]->title}</originaltitle>\n";
        $metadata.="    <sorttitle>{$movieinfo[0]->title}</sorttitle>\n";
        $metadata.="    <rating>{$movieinfo[0]->rating}</rating>\n";
        $metadata.="    <year>{$movieinfo[0]->year}</year>\n";
        $metadata.="    <votes>{$movieinfo[0]->rating_count}</votes>\n";
        $metadata.="    <outline>{$movieinfo[0]->plot_simple}</outline>\n";
        $metadata.="    <plot>{$movieinfo[0]->plot_simple}</plot>\n";
        $metadata.="    <tagline>{$movieinfo[0]->plot_simple}</tagline>\n";
        $metadata.="    <runtime>{$movieinfo[0]->runtime[0]}</runtime>\n";
        $metadata.="    <thumb>{$movieinfo[0]->poster->cover}</thumb>\n";
        $metadata.="    <genre>{$movieinfo[0]->genres[0]}</genre>\n";
        $metadata.="    <director>{$movieinfo[0]->directors[0]}</director>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[0]}</name></actor>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[1]}</name></actor>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[2]}</name></actor>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[3]}</name></actor>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[4]}</name></actor>\n";
        $metadata.="    <actor><name>{$movieinfo[0]->actors[5]}</name></actor>\n";
        $metadata.="</movie>\n";
        file_put_contents($path . "/movie.nfo", $metadata);
    }

    /**
     * Disable file/folder by renaming it
     *
     * @param type $file filename or directory to rename by trying to add -
     */
    public function disable($file, $reason = '[unk]') {
        $add = "-";
        while (file_exists($add . $file)) {
            $add.="-";      // add - in front of the file name to disable it!
        }
        $path_part = explode("/", $file);
        $part_end = $path_part[count($path_part) - 1];
        $file_new = str_replace("/" . $part_end, "/" . $add . " " . $reason . " " . $part_end, $file);
        if (!DEBUG_SIMULATE)
            rename($file, $file_new); // rename file
    }

    /**
     * Main entry for sort
     *
     * Returns nothing
     */
    public function run() {
        $sourcedir = $this->config["Directories"]["source"];
        if (!file_exists($sourcedir)) {
            $this->log->addmessage("Source directory does not exists, please configure path!");
            return false;
        }
        $sdirs = $this->files->get_folder($sourcedir);
        foreach ($sdirs as $sdir => $sdir_val) {
            if ($sdir[0] == "-")    // skip already processed and unrecognized content
                continue;
            $this->log->addmessage("Processing {$sdir}");
            $directory = $sdir_val["directory"];    // is content a directory or file?
            $tv_name = $this->tv_parse($sdir);  // find tv info
            if (!$tv_name) {    // Detected movie
                $pass = $this->check_filters($sdir);
                if (!$pass) {
                    $this->disable($this->config["Directories"]["source"] . "/" . $sdir, "[filter-" . $this->filter_reject_reason . "]");   // disable content that does not pass the filter
                    continue;
                }
                $newname = $this->parse_name($sdir);    // clean name
                if (empty($newname)) {
                    $this->log->addmessage("Parsing name '{$sdir}' mismatch, continue");
                    continue;
                }
                $movieinfo = $this->imdb->get_movie_by_title($newname);
                if (!$movieinfo || $movieinfo->code == 404) {
                    $this->log->addmessage("No IMDB information for: {$newname}, skipping");
                    $this->disable($this->config["Directories"]["source"] . "/" . $sdir, "[imdb not found]");   // disable unknown content
                    continue;
                }
                $imdb_name = "{$movieinfo[0]->title} ({$movieinfo[0]->year})";
                $this->log->addmessage("Detected name: {$newname} IMDB: {$imdb_name}");
                if ($this->config["IMDB"]["use_imdb_rename"] == 1)
                    $newname = $imdb_name;
                $existing = $this->db->downloaded_content_exist($newname, false, false, true, false);
                if ($existing) {
                    $this->log->addmessage("Already exists: {$newname} IMDB: {$imdb_name}");
                    //$this->disable($this->config["Directories"]["source"] . "/" . $sdir);   // disable already existing content
                    $this->files->delTree($this->config["Directories"]["source"] . "/" . $sdir);
                    continue;
                }
            } else
            if ($tv_name["season"] && $tv_name["episode"]) {    // Detected TV
                $newname = false;
                $this->log->addmessage("Detected tv: {$tv_name["name"]} Season {$tv_name["season"]} Episode {$tv_name["episode"]}");
                $existing = $this->db->downloaded_content_exist($tv_name["name"], $tv_name["season"], $tv_name["episode"], true, false);
                if ($existing) {
                    $this->log->addmessage("Already exists: {$tv_name["name"]} Season {$tv_name["season"]} Episode {$tv_name["episode"]}");
                    //$this->disable($this->config["Directories"]["source"] . "/" . $sdir);   // disable already existing content
                    $this->files->delTree($this->config["Directories"]["source"] . "/" . $sdir);
                    continue;
                }
            }
            if (!$newname && !$tv_name) {   // Not detected as movie or tv
                $this->log->addmessage("Not detected as content");
                $this->disable($this->config["Directories"]["source"] . "/" . $sdir, "[not tv or movie]");   // disable unknown content
                continue;
            }
            if ($directory) {   // Content is in directory
                $subfolder = $this->files->get_folder($this->config["Directories"]["source"] . "/" . $sdir . "/");     // get files on dir
                if (empty($subfolder)) {
                    $this->log->addmessage("Empty folder, deleted: " . $this->config["Directories"]["source"] . "/" . $sdir . "/");
                    rmdir($this->config["Directories"]["source"] . "/" . $sdir);
                    continue;
                }
                $subfolder = $this->files->process_subfolder($this->config["Directories"]["source"] . "/" . $sdir . "/", $subfolder);
                if (empty($subfolder)) {
                    $this->log->addmessage("No usable files found in {$sdir}");
                    $this->disable($this->config["Directories"]["source"] . "/" . $sdir, "[no usable files]");   // disable unknown content
                    continue;
                }
            } else {    // Content is file
                $subfolder = $this->files->process_file($this->config["Directories"]["source"] . "/" . $sdir);
                if (empty($subfolder)) {
                    $this->log->addmessage("Not a usable file {$sdir}");
                    $this->disable($this->config["Directories"]["source"] . "/" . $sdir, "[not usable file]");   // disable unknown content
                    continue;
                }
            }
            $this->move_files($newname, $tv_name, $subfolder, $movieinfo);      // rename/move files to a new location
            if ($this->config['IMDB']['download_metadata'] == 1 && !$tv_name)  // download metadata if set, and not tv
                $this->download_metadata($this->config["Directories"]["destination"] . "/" . $newname, $movieinfo);
        }
    }

    /**
     * Move files and insert into DB, $name or $tv must be set
     *
     * @param string $name
     * @param string $tv
     * @param array $files
     * @param array imdb
     * @return boolean
     */
    private function move_files($name, $tv, $files, $imdb) {
        if ($name) {    // Detected as movie
            $minimum_filesize = $this->size_to_number($this->config["Quality"]["minimum_file_size"]);
            $maximum_filesize = $this->size_to_number($this->config["Quality"]["maximum_file_size"]);
            $destination = $this->config["Directories"]["destination"] . "/" . $name;
            foreach ($files as $file) {
                $filename = pathinfo($file, PATHINFO_FILENAME) . "." . pathinfo($file, PATHINFO_EXTENSION);
                $file_path = pathinfo($file, PATHINFO_DIRNAME);
                $file_path_array = $this->path2array($file_path);
                $base_path_array = $this->path2array($this->config["Directories"]["source"]);
                $remove_path = count($file_path_array) > count($base_path_array);

                $fdestination = $destination . "/" . $filename;
                $filesize = $this->getsize($file);
                if ((int) $filesize < $minimum_filesize || (int) $filesize > $maximum_filesize) {
                    $this->log->addmessage("File size mismatch, {$filesize} while limit is min {$minimum_filesize}, max {$maximum_filesize}");
                    if ($remove_path)
                        $this->disable($file_path, "[fsize mismatch]");   // disable file size mismatch folder
                    else
                        $this->disable($file, "[fsize mismatch]");   // disable file size mismatch file
                    continue;
                }
                $this->log->addmessage("Copy/move file {$file} -> {$fdestination} [{$name}]");
                // Make destination folder
                if ($this->config["Debug"]["level"] < 1 && !DEBUG_SIMULATE)
                    mkdir($destination, 0777, true);    // Make destination with flags 0777 on linux (rwx for all)
                if ($this->config["Options"]["copy_delete_files"] == 1) {   // safer, more compatible, painfully slow
                    if ($this->config["Debug"]["level"] < 1)
                        if (!copy($file, $fdestination))
                            continue;       // if copy does not suceed it may still be used by some other process, so skip it and wait for next call




                        
                } else if ($this->config["Options"]["move_files"] == 1) {   // MUCH faster, in fact almost instant, use only if source and dest are on same partition
                    if ($this->config["Debug"]["level"] < 1)
                        if (!rename($file, $fdestination))
                            continue;       // if rename does not suceed it may still be used by some other process, so skip it and wait for next call




                        
                }
                if ($this->config["Debug"]["level"] < 1 && $remove_path)
                    $this->files->delTree($file_path);
                if ($this->config["Debug"]["level"] < 2)
                    $this->db->add_new_content($name, "", "", $filesize, $imdb, $this->quality);
            }   // foreach files
        } else
        if ($tv) {      // Detected as TV
            $tv_name = $tv["name"];
            $tv_season = $tv["season"];
            $tv_episode = $tv["episode"];
            $dir = $this->config["Directories"]["destination_tv"] . "/" . $tv_name . "/Season " . $tv_season;
            $minimum_filesize = $this->size_to_number($this->config["Series"]["minimum_file_size"]);
            $maximum_filesize = $this->size_to_number($this->config["Series"]["maximum_file_size"]);
            if ($this->config["Debug"]["level"] < 1 && !DEBUG_SIMULATE)
                mkdir($dir, 0777, true);    // Make destination with flags 0777 on linux (rwx for all)
            foreach ($files as $file) {
                $filename = "{$tv_name}_S{$tv_season}_E{$tv_episode}." . pathinfo($file, PATHINFO_EXTENSION);
                $file_path = pathinfo($file, PATHINFO_DIRNAME);
                $file_path_array = $this->path2array($file_path);
                $base_path_array = $this->path2array($this->config["Directories"]["source"]);
                $remove_path = count($file_path_array) > count($base_path_array);

                $fdestination = $dir . "/" . $filename;
                $filesize = $this->getsize($file);
                if ((int) $filesize < $minimum_filesize || (int) $filesize > $maximum_filesize) {
                    $this->log->addmessage("File size mismatch, {$filesize} while limit is min {$minimum_filesize}, max {$maximum_filesize}");
                    if ($remove_path)
                        $this->disable($file_path, "[fsize mismatch]");   // disable file size mismatch folder
                    else
                        $this->disable($file, "[fsize mismatch]");   // disable file size mismatch file
                    continue;
                }
                $this->log->addmessage("Rename/Moving file {$file} -> {$fdestination} [{$name}]");
                // Do we want to copy and delete or move files?
                if ($this->config["Options"]["copy_delete_files"] == 1) {   // safer, more compatible, painfully slow
                    if ($this->config["Debug"]["level"] < 1) {  // do not touch files if level1 or higher
                        if (!copy($file, $fdestination))
                            continue;       // if copy does not suceed it may still be used by some other process, so skip it and wait for next call
                    }
                } else if ($this->config["Options"]["move_files"] == 1) {   // MUCH faster, in fact almost instant, use only if source and dest are on same partition
                    if ($this->config["Debug"]["level"] < 1 && !DEBUG_SIMULATE) {  // do not touch files if level1 or higher
                        if (!rename($file, $fdestination))
                            continue;       // if rename does not suceed it may still be used by some other process, so skip it and wait for next call
                    }
                }
                if ($this->config["Debug"]["level"] < 1 && $remove_path)
                    $this->files->delTree($file_path);
                if ($this->config["Debug"]["level"] < 2)
                    $this->db->add_new_content($tv_name, $tv_season, $tv_episode, $filesize, $imdb, $this->quality);
            }   // foreach files
        }
    }

    /**
     * Convert path to array by spliting it
     * 
     * @param type $path
     */
    private function path2array($path) {
        $path = str_replace("\\\\", "/", $path);
        $path = str_replace("\\\\", "/", $path);
        $path = str_replace("\\", "/", $path);
        $patha = explode("/", $path);
        $patha = array_filter($patha);
        return $patha;
    }

    /**
     * Convert to human readable number
     * 
     * @param int $size Number to convert
     * @return string Human readable format 
     */
    public function size_to_number($size) {
        $size = str_replace("k", "000", strtolower($size));
        $size = str_replace("m", "000000", strtolower($size));
        $size = str_replace("g", "000000000", strtolower($size));
        $size = str_replace("t", "000000000000", strtolower($size));
        return $size;
    }

    /**
     * Find year match in regex
     * 
     * @param type $name
     * @return boolean
     */
    public function getyear($name) {
        $matched = preg_match('/(19|20)\d{2}\b/i', $name, $match);
        if (!$matched)
            return false;
        $year = $match[0];
        return $year;
    }

    /**
     * Detect TV episode and returns details
     *
     * @param type $name filename of the content to check if it's tv episode
     * @return mixed false if content is not detected as tv episode, otherwise returns tv episode info
     */
    public function tv_parse($name) {
        $air_date = false;
        $cname = strtolower($name);
        $cname = str_replace($this->for_replace, " ", $cname);
        foreach ($this->months as $month => $num) {
            $cname = str_replace($month, $num, $cname);
        }
        $matched1 = preg_match('/s\d{2}e\d{2}\b/i', $cname, $match1);  //S01E01
        $matched2 = preg_match('/\d{1}x\d{2}\b/i', $cname, $match2);  //1x01
        $matched3 = preg_match('/\d{1}x\d{1}\b/i', $cname, $match3);  //1x1
        $matched4 = preg_match('/(19|20)\d{2} \d{2} \d{2}\b/i', $cname, $match4);  //2013.02.15
        $matched5 = preg_match('/\d{2}x\d{2}\b/i', $cname, $match5);  //10x01
        $matched6 = preg_match('/\d{2} \d{2} (19|20)\d{2}\b/i', $cname, $match6);  //15.02.2013
        if (!$matched1 && !$matched2 && !$matched3 && !$matched4 && !$matched5 && !$matched6)
            return false;
        if ($matched1) {
            $pos = strpos($cname, $match1[0]);
            $name = trim(substr($cname, 0, $pos));
            $season = $match1[0][1] . $match1[0][2];
            $episode = $match1[0][4] . $match1[0][5];
        }
        if ($matched2) {
            $pos = strpos($cname, $match2[0]);
            $name = trim(substr($cname, 0, $pos));
            $season = $match2[0][0];
            $episode = $match2[0][2] . $match2[0][3];
        }
        if ($matched3) {
            $pos = strpos($cname, $match3[0]);
            $name = trim(substr($cname, 0, $pos));
            $season = $match3[0][0];
            $episode = $match3[0][2];
        }
        if ($matched4) {
            $pos = strpos($cname, $match4[0]);
            $name = trim(substr($cname, 0, $pos));
            $air_date = $match4[0];
            $air_date = $air_date[8] . $air_date[9] . "." . $air_date[5] . $air_date[6] . "." . $air_date[0] . $air_date[1] . $air_date[2] . $air_date[3];
        }
        if ($matched5) {
            $pos = strpos($cname, $match5[0]);
            $name = trim(substr($cname, 0, $pos));
            $season = $match5[0][0] . $match5[0][1];
            $episode = $match5[0][3] . $match5[0][4];
        }
        if ($matched6) {
            $pos = strpos($cname, $match6[0]);
            $name = trim(substr($cname, 0, $pos));
            $air_date = $match6[0];
        }
        if ($air_date) {
            $ep = $this->tvrage->airdate_to_episode($name, $air_date);
            $name = $ep[0];
            $season = $ep[1];
            $episode = $ep[2];
        }
        if (!$season && !$airdate)
            return false;
        $name = $this->clear_bracket($name);
        $name = $this->name_start_cleanup($name);
        $tvdata = array(
            "name" => $name,
            "season" => $season,
            "episode" => $episode,
        );
        return $tvdata;
    }

    /**
     * Detect and remove brackets from name
     * Example [ www.mycoolsite.com ] Terminator (1995)
     *
     * @param type $name
     * @return type
     */
    private function clear_bracket($name) {
        $bracket1 = strpos($name, "[");
        $bracket2 = strpos($name, "]");
        if (!$bracket1 && !$bracket2) {
            $bracket1 = strpos($name, "(");
            $bracket2 = strpos($name, ")");
        }
        if (!$bracket1 && !$bracket2) {
            $bracket1 = strpos($name, "{");
            $bracket2 = strpos($name, "}");
        }
        if (!$bracket1 && !$bracket2)
            return $name;       // no brackets
        if ($bracket1 > 2)
            return $name;
        $inbracket = trim(substr($name, $bracket1 + 1, $bracket2 - $bracket1 - 1));
        if ((int) $inbracket > 1900 && (int) $inbracket < 2100)   // someone put name in bracket O.o
            return $name;
        $str1 = substr($name, 0, $bracket1);
        $str2 = substr($name, $bracket2 + 1);
        $name_nobrackets = $str1 . $str2;
        return trim($name_nobrackets);
    }

    private function name_start_cleanup($name) {
        $notallowed = array("", " ", ".", "-", "=", "+", "_");
        while (in_array($name[0], $notallowed))
            $name = substr($name, 1);
        return $name;
    }

    public function parse_name($name) {
        $name_clean = strtolower($name);
        $name_clean = $this->clear_bracket($name_clean);
        $name_clean = $this->name_start_cleanup($name_clean);
        $name_clean = str_replace($this->for_replace, " ", $name_clean);
        $name_clean = str_replace($this->for_replace2, " ", $name_clean);
        $year = $this->getyear($name_clean);
        if (!$year) {
            $this->filter_reject_reason = "no year";
            return false;
        }
        if ($this->config["Processing"]["starting_year"] > $year || $this->config["Processing"]["ending_year"] < $year) {
            $this->filter_reject_reason = "wrong year";
            $this->log->addmessage("Year mismatch, {$year} ({$this->config["Processing"]["starting_year"]}-{$this->config["Processing"]["ending_year"]})");
            return false;
        }
        $ypos = strpos($name_clean, $year);
        if ($ypos < 2) {
            $this->filter_reject_reason = "no name before year";
            return false;
        }
        $realname = substr($name_clean, 0, $ypos);
        $realname = trim(str_replace($this->for_replace2, " ", $realname));
        $realname.=" ($year)";
        for ($c = 1; $c < 5; $c++) {
            $realname = str_replace("  ", " ", $realname);
        }
        $tags = trim(substr($name_clean, $ypos + 5));
        for ($c = 1; $c < 5; $c++) {
            $tags = str_replace("  ", " ", $tags);
        }
        $tags = explode(" ", $tags);
        $this->tags = $tags;
        return $realname;
    }

    /**
     * Check if tv content is matched filters
     *
     * @param type $name filename of the content to be checked
     * @return boolean
     * Returns true if matched filters, false if not
     */
    public function check_filters_tv($name) {
        //$minimum_filesize = $this->size_to_number($this->config["Series"]["minimum_file_size"]);
        //$maximum_filesize = $this->size_to_number($this->config["Series"]["maximum_file_size"]);
        return true;
    }

    /**
     * Check if content is matched filters
     *
     * @param type $name filename of the content to be checked
     * @return boolean
     * Returns true if matched filters, false if not
     */
    public function check_filters($name) {
        $detected_quality = "";
        $unwanted_content = false;
        $name_clean = $this->parse_name($name);
        if (!$name_clean)
            return false;
        foreach ($this->tags as $tag) {
            foreach ($this->qualities as $quality) {
                if ($quality == $tag) {
                    $detected_quality = $tag;
                    break;
                }
            }
            foreach ($this->config["Processing"]["unwanted_content"] as $ucontent) {
                if ($ucontent == $tag) {
                    $unwanted_content = $tag;
                    break;
                }
            }
        }
        if ($unwanted_content) {
            $this->filter_reject_reason = "unwanted";
            $this->log->addmessage("Unwanted content in name {$name} ({$unwanted_content})");
            return false;
        }
        $quality_index = array_search($detected_quality, $this->qualities);
        $minimum_quality_index = array_search($this->config["Quality"]["minimum_quality"], $this->qualities);
        $maximum_quality_index = array_search($this->config["Quality"]["maximum_quality"], $this->qualities);
        if ($quality_index < $minimum_quality_index || $quality_index > $maximum_quality_index) {
            $this->filter_reject_reason = "quality";
            $this->log->addmessage("Content {$name} does not meet minimum or maximum quality!");
            return false;
        }

        $imdb = $this->imdb->get_movie_by_title($name_clean);
        if ($imdb != NULL && is_array($imdb) && is_object($imdb[0])) {    // if imdb content is matched and found, if not ignore rules
            $imdb_rating = $imdb[0]->rating;
            $imdb_rating_count = $imdb[0]->rating_count;
            $imdb_genres = $imdb[0]->genres;
            $imdb_poster = $imdb[0]->poster->cover;
            $imdb_url = $imdb[0]->imdb_url;
            $imdb_release_date = $imdb[0]->release_date;
            if ($imdb_rating != NULL && $imdb_rating < $this->config["IMDB"]["minimum_rating"] && $this->config["IMDB"]["minimum_rating"] > 0) {
                $this->filter_reject_reason = "rating";
                $this->log->addmessage("Content {$name_clean} does not meet minimum rating!");
                return false;
            }
            if ($imdb_rating_count != NULL && $imdb_rating_count < $this->config["IMDB"]["minimum_rating_count"] && $this->config["IMDB"]["minimum_rating_count"] > 0) {
                $this->filter_reject_reason = "votes";
                $this->log->addmessage("Content {$name_clean} does not meet minimum votes!");
                return false;
            }
        }
        $this->imdb_info = $imdb;
        $this->quality = $detected_quality;
        return true;
    }

}

?>